package com.rp.system.controller;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.rp.common.utils.JsonUtil;
import com.rp.common.utils.RpUtil;
import com.rp.controller.RpController;
import com.rp.infopub.po.Channel;
import com.rp.system.po.DatasourceConfig;
import com.rp.system.service.DataImportService;
import com.rp.system.service.MenuService;

@Controller
@RequestMapping("/rp/system/baseData/")
public class BaseDataController extends RpController{
	
	@Autowired
	private MenuService menuService;
	@Autowired
	private DataImportService dataImportService;

	@RequestMapping("main")
	public ModelAndView main(){
		model.put("webpageTitle", "基础数据维护");
		return forward("/rp/system/baseData/main.jsp");
	}
	
	/**
	 * 测试数据源连接
	 * @return
	 */
	@ResponseBody
	@RequestMapping("testDsLink")
	public String testDsLink(String dbType, String url, String username, String password){
		if(RpUtil.testDsLink(dbType, url, username, password)){
			return SUCCESS;
		}
		return ERROR;
	}
	
	@ResponseBody
	@RequestMapping("dataImport")
	public String dataImport(String json, @RequestParam(required=false)String targetChannelId){
		try{
			Map<String, Object> data = JsonUtil.jsonToMap(json);
			
			DatasourceConfig dc = new DatasourceConfig();
			dc.setDbType((String)data.get("dbType"));
			dc.setUrl((String)data.get("url"));
			dc.setUsername((String)data.get("username"));
			dc.setPassword((String)data.get("password"));
			
			if(((String)data.get("menuAbout")).equals("true"))
				dataImportService.importMenu(dc);
			if(((String)data.get("systemModule")).equals("true"))
				dataImportService.importModule(dc);
			if(((String)data.get("systemAuthority")).equals("true"))
				dataImportService.importAuthority(dc);
			if(((String)data.get("systemResource")).equals("true"))
				dataImportService.importResource(dc);
			if(((String)data.get("systemRole")).equals("true"))
				dataImportService.importRole(dc);
			
			
			if(((String)data.get("infoChannel")).equals("true"))
				dataImportService.importChannel(dc);
			if(((String)data.get("infoArticle")).equals("true"))
				dataImportService.importArticle(dc, targetChannelId);
			
			
		}catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
		
		return SUCCESS;
	}
	
	@ResponseBody
	@RequestMapping("getTargetChannels")
	public List<Channel> getTargetChannels(
			String dbType,String url,String username,String password){
		DatasourceConfig dc = new DatasourceConfig(dbType, url, username, password);
		return dataImportService.getTargetDbChannels(dc);
	}
	
}
